package com.project.frba.bifront.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.project.frba.bi.BiUtil;
import com.project.frba.bi.descriptor.DescriptorsLoader;

public class UploadServer extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{			
			String fileName = request.getRequestURI().split("/")[3];
			StringBuffer repositoryPath = new StringBuffer(BiUtil.getRepositoryPath());
			if (fileName.endsWith("_descriptor.xml")) {
				repositoryPath.append("upload/descriptors/");
			}
			File repository = new File(repositoryPath.toString());
			
			File requestedFile = new File(repository, fileName);
			String fileExtension = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
			
			if("xml".equals(fileExtension)){
				fileExtension = new String("application/xml");
			}
			
			if(requestedFile.exists()){
				response.setContentType(request.getSession().getServletContext().getMimeType(fileExtension));				
				OutputStream outResponse = response.getOutputStream();
				BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(requestedFile));
				
				byte[] buffer = new byte[1024];
				int n;
				while ( (n=inputStream.read(buffer)) > -1) {
					outResponse.write(buffer, 0, n);
				}
				inputStream.close();
				outResponse.close();
			}
		} catch (Exception e) {
			System.out.println("UploadServer: downloading problems...." + request.getRequestURI().split("/")[3]);
			e.printStackTrace();
		}		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			FileItemFactory itemFactory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(itemFactory);
            List items = upload.parseRequest(request);
			Iterator iter = items.iterator();
			
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				String file = this.upload(new BufferedInputStream(item.getInputStream()), item.getName()); 
			}
			
			response.setContentType("text/xml");
			response.getWriter().write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><response success=\"true\" ><data><responseMsg>this is a message</responseMsg></data></response>");
		} catch (Throwable e) {
			System.out.println("UploadServer: uploading problems....");
			response.setContentType("text/xml");
			response.getWriter().write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><response success=\"false\"><data><responseMsg>thisiserrormessage</responseMsg></data></response>");
		} finally {
			DescriptorsLoader.reload();
		}
				
	}

	private String upload(InputStream is, String fileName) throws IOException {
		File repo = new File(BiUtil.getRepositoryPath());
		StringBuffer folder = new StringBuffer("upload");
		if(fileName.endsWith("_descriptor.xml")){
			folder.append("/descriptors");
		}
		File outputDir = new File(repo, folder.toString());
		
		OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(outputDir, fileName)));
		byte[] buffer = new byte[1024];
		int n;
		while ( (n=is.read(buffer)) > -1) {
			os.write(buffer, 0, n);
		}
		is.close();
		os.close();
		
		if(fileName.endsWith("_descriptor.xml")) {
			DescriptorsLoader.reload();
		}
		return outputDir.getAbsolutePath() + "/" + fileName;
	}


}
